from dbUtils import dbMysql, dbMongo, dbRedis,tp_SQL
from flask import g
import datetime,json
from datetime import timedelta

class MarketModel():
    def __init__(self):
        pass

    @classmethod
    def DailyMoneyQuery(cls, startDate, endDate):
        return dbMysql.db_Mysql.QueryDB(sql=tp_SQL.sql_daily_money_sum.format(startDate,endDate))

    @classmethod
    def DailyGoodsMarketQuery(cls, date=None):
        return dbMysql.db_Mysql.QueryDB(sql=tp_SQL.sql_daily_income.format(date))

    @classmethod
    def Daily3DMarketQuery(cls):
        today = (datetime.date.today() + timedelta(days=-30)).strftime("%Y-%m-%d")
        today6 = (datetime.date.today() + timedelta(days=-36)).strftime("%Y-%m-%d")
        res = dbMysql.db_Mysql.QueryDB(sql=tp_SQL.sql_3d.format(today6, today))
        data = [list(item) for item in res]
        return data

    @classmethod
    def GoodsTotalMoneyOrder(cls):
        return dbMysql.db_Mysql.QueryDB(sql=tp_SQL.sql_goods_stat_order)

    @classmethod
    def GoodsTotalMoneyQuery(cls):
        return dbMysql.db_Mysql.QueryDB(sql=tp_SQL.sql_goods_stat)

    @classmethod
    def firstDayQuery(cls):
        return dbMysql.db_Mysql.QueryDB(sql=tp_SQL.sql_newDate)

    def DataQueryMysql(self, sql=None):
        res = dbMysql.db_Mysql.QueryDB(sql)
        return res
    '''
        查询所有商品销售收入，第一次从mysql中读取，后续从mongo中读取
    '''
    def DataQueryMongoByGoodsTotalOrder(self,choice=None):
        data = dbMongo.DBMongo().QueryDB(collection='GoodsMoneyOrder')
        if not data:
            print("不从mongo读，从mysql读...")
            name = [item[0] for item in self.GoodsTotalMoneyOrder()]
            money = [str(item[1]) for item in self.GoodsTotalMoneyOrder()]
            mydict = {
                "result":str(json.dumps(dict(zip(name, money))))
            }
            dbMongo.DBMongo().SetData(collection='GoodsMoneyOrder',params=mydict)
        return data['result']

    def DataQueryMongoByGoodsTotal(self):
        data = dbMongo.DBMongo().QueryDB(collection='GoodsTotalMoney')
        if not data:
            print("不从mongo读，从mysql读...")
            name = [item[0] for item in self.GoodsTotalMoneyQuery()]
            money = [str(item[1]) for item in self.GoodsTotalMoneyQuery()]
            mydict = {
                "result": str(json.dumps(dict(zip(name, money))))
            }
            dbMongo.DBMongo().SetData(collection='GoodsTotalMoney', params=mydict)
        return data['result']

    '''
        查询每日各商品销售收入，第一次从mysql中读取，后续从redis缓存中读取
    '''
    def DataQueryRedisByDay1(self,key=None,item1=None):
        '''
          前端读取从redis这，如果没有就从mysql里读，参数中key为统计类型名，处理每日各商品统计收入数据
        :return:
        '''
        res = dbRedis.DBRedis().QueryDB(key=key,name=item1)
        if not res:
            print("不从redis中读取,从mysql中读取。。。。")
            res = self.DailyGoodsMarketQuery(date=item1)
            name = [item[1] for item in res]
            money = [str(item[2]) for item in res]
            data = json.dumps(dict(zip(name, money)))
            dbRedis.DBRedis().SetDB(key=key,field=item1,value=data)
        else:
            print("从redis中读取...")
            data = res
        return data

    def DataQueryRedisByInterval(self,key=None,item1=None,item2=None):
        '''
          前端读取从redis这，如果没有就从mysql里读，参数中key为统计类型名，item1和item2分别为日期项
          处理某时间段内显示每日总收入
        :return:
        '''
        res = dbRedis.DBRedis().QueryDB(key=key,name=item1+'-'+item2)
        if not res:
            print("从rmysql中读取...")
            res = self.DailyMoneyQuery(item1,item2)
            date = [item[0] for item in res]
            money = [str(item[1]) for item in res]
            data = json.dumps(dict(zip(date, money)))
            dbRedis.DBRedis().SetDB(key=key, field=item1+'-'+item2, value=data)
        else:
            print("从redis中读取...")
            data = res
        return data



